import Taro, { useRouter } from '@tarojs/taro';
import { View, Text, Button } from '@tarojs/components';
import { useEffect, useState } from 'react'
import { STATUS, courseInfo, studentInfo } from '../../configProvider';
import './index.scss'
import CourseCard from '../../components/Card/CourseCard';

const CheckTeacherView: React.FC = () => {
  const router = useRouter();
  const { courseId } = router.params;
  const [course, setCourse] = useState<courseInfo>();
  const [checkedStudents, setCheckedStudents] = useState<string[]>([]);
  const [uncheckedStudents, setUncheckedStudents] = useState<string[]>([]);
  const [leaveStudents, setLeaveStudents] = useState<string[]>([]);
  const [studentMap, setStudentMap] = useState({});

  useEffect(() => {
    getStudentMap();
    if (!courseId) {
      console.log('more argus are needed');
      return;
    }
    // 查询数据库中的 course 表，获取 check 字段的最后一个对象的 students 数组
    Taro.cloud
      .callFunction({
        name: 'getCourse',
        data: {
          courseId: courseId,
        },
      })
      .then((res) => {
        console.log('queryCourse success', res, courseId);
        if (typeof res.result === 'object' && res.result.code === 0) {
          const course: courseInfo = res.result.data;
          setCourse(course);
          const lastCheck = course.check[course.check.length - 1];
          const checkedStudents = lastCheck.students;
          const leaveStudents = lastCheck.leaveStudents ?? [];
          const allStudents = course.students;
          setCheckedStudents(checkedStudents);
          setLeaveStudents(leaveStudents);
          setUncheckedStudents(allStudents.filter((student) => (!checkedStudents.includes(student) && !leaveStudents.includes(student))));
        } else {
          console.log('queryCourse fail', typeof res.result === 'object' ? res.result.message : '查询失败');
        }
      })
      .catch((err) => {
        console.log('queryCourse fail', err);
      });
  }, []);

  const getStudentMap = () => {
    Taro.cloud.callFunction({
      // 要调用的云函数名称
      name: 'getStudentList',
      // 传递给云函数的event参数
      data: {}
    }).then((res: any) => {
      let map = {}
      res.result.forEach((value: studentInfo) => {
        map[value.code] = value.name
      })
      console.log(map)
      setStudentMap(map)
    }).catch(err => {
      console.log('fail to call getStudentList', err)
    })
  };

  const StudentList = (students: string[]) => {
    return students.sort((a, b) => {
      return a > b ? 1 : -1
    }).map((student) => (
      <View className='student-list-item' key={student}>
        <Text>{studentMap[student]}</Text>
        <Text>{student}</Text>
      </View>
    ))
  }

  const stopCheck = () => {
    Taro.showModal({
      title: '提示',
      content: `关闭课程'${course?.courseName}'的点名？`,
      success: function (res) {
        if (res.confirm) {
          console.log('用户点击确定')
          Taro.cloud.callFunction({
            name: 'changeCourseState',
            data: {
              _id: courseId,
              action: 'stop',
            },
          }).then((res) => {
            console.log('changeCourseState', res);
            Taro.showToast({
              title: '关闭成功',
              icon: 'success',
              duration: 1000,
            }).then(() => {
              setTimeout(() => {
                Taro.reLaunch({ url: '../index/index' });
              }, 1000);
            });
          }).catch((err) => {
            console.log('fail to call changeCourseState', err);
          });
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  }

  return (
    <View className='history-detail'>
      {course && <CourseCard name={course.courseName} startTime={course.startTime}
        endTime={course.endTime} weekday={course.weekday} teacher={course.teacher}
        status={STATUS.TEACHER} startDate={course.startDate} endDate={course.endDate} />
      }
      <View className='common-title'>签到方式：{course?.method}</View>
      {course && course.method === '验证码' && <View className="common-card input-container">
        <Text>验证码:</Text>
        <Text className='input'>{course.verifyCode}</Text>
      </View>}
      <Button className='common-button' onClick={stopCheck}>关闭点名</Button>

      <View className='history-detail-box'>
        <Text className='common-title'>
          已签到{checkedStudents.length}人：
        </Text>
        {StudentList(checkedStudents)}
      </View>
      <View className='history-detail-box'>
        <Text className='common-title'>
          未签到{uncheckedStudents.length}人：
        </Text>
        {StudentList(uncheckedStudents)}
      </View>
      <View className='history-detail-box'>
        <Text className='common-title'>
          已请假{leaveStudents.length}人：
        </Text>
        {StudentList(leaveStudents)}
      </View>
    </View>
  );
};

export default CheckTeacherView;
